<template>
  <div class="totalSearch">
    <!-- 头部搜索 -->
    <div class="searchFather" :class="{ active: !isSearch && keyword.length > 0}">
      <van-search
        class="search"
        v-model="keyword"
        @cancel="onCancel"
        placeholder="请输入商品名称"
        @clear="clear"
        @input="input"
        @focus="focus"
        clear-trigger="always"
        :show-action="isSearch"
        @search="onSearch"
      ></van-search>
      <!-- 下拉菜单 -->
      <van-dropdown-menu v-if="!isSearch && keyword.length > 0" class="diopDownItem">
        <van-dropdown-item title="综合">
          <div class="detault" @click="categoryRequest(0,0)">默认排序</div>
        </van-dropdown-item>
        <van-dropdown-item title="价格" ref="item">
          <div class="content">
            <span>筛选</span>
            <input type="text" placeholder="最低价" v-model="floorPrice" />
            <span>—</span>
            <input type="text" placeholder="最高价" v-model="upperPrice"/>
          </div>
          <div class="sort">
            <span>排序</span>
            <button class="button" @click="changeSort(1)"    :class="{'active':descSorted === 1}">从低到高</button>
            <button class="button" @click="changeSort(2)" :class="{'active':descSorted === 2}">从高到底</button>
          </div>
          <button class="no" @click="onConfirm(false)">取消</button>
          <button class="yes" @click="onConfirm(true)">确定</button>
        </van-dropdown-item>
        <van-dropdown-item title="分类">
          <van-tag
            class="vantTag"
            :color="index === currentIndex ? '#dd1a21' : '#7f7f7f'"
            @click="categoryRequest(category.id,index)"
            :text-color="index === currentIndex ? '#dd1a21' : '#333333'"
            v-for="(category,index) in category1List "
            :key="category.id"
            plain
            size="large"
            >{{category.name}}</van-tag
          >

        </van-dropdown-item>
      </van-dropdown-menu>
    </div>
    <!-- 设置X图标并且带事件 -->
    <!-- <van-search v-model="value" clearable @clear='clear' ></van-search> -->

    <!-- 底部存储区 -->
    <div class="footer" v-show="!keyword.length">
      <!-- 存储历史记录 -->
      <div class="storage" v-show="historyList.length">
        <div class="header">
          <span class="text">历史记录</span>
          <van-icon name="delete-o" @click="clearhHistoryList" />
        </div>
        <div class="navList">
          <van-tag
            text-color="#333333"
            color="#999999"
            size="large"
            plain
            type="primary"
            @click="totalGetGoods(history)"
            v-for="(history,index) in historyList"
            :key="index"
            >{{history}}</van-tag
          >
        
        </div>
      </div>
      <!-- 热门搜索 -->
      <div class="popular">
        <div class="header">
          <span class="text">热门搜索</span>
        </div>
        <div class="navList">
          <!-- #dd1a21 -->
          <van-tag
          @click="popularGoods(popular.keyword)"
            :text-color="index === 0 ? '#dd1a21' : '#333333'"
            :color="index === 0 ? '#dd1a21' : '#999999'"
            size="large"
            plain
            type="primary"
            v-for="(popular, index) in popularList"
            :key="index"
            >{{ popular.keyword }}</van-tag
          >
        </div>
      </div>
    </div>

    <!-- 输入时展示区 -->
    <div class="navigation" v-show="isSearch && keyword.length > 0">
      <van-cell @click="totalGetGoods(nav)" v-for="(nav,index) in navList " :key='index' :title="nav" is-link value="" />


    </div>

    <!-- 商品展示区  -->
    <div class="exhibition" v-if="!isSearch && keyword.length > 0">
      <GoodsList :keyword.sync='keyword' :isSearch='isSearch'></GoodsList>

    </div>
  </div>
</template>

<script>
import {
  Search,
  Icon,
  Tag,
  Cell,
  DropdownMenu,
  DropdownItem,
  Switch,
} from "vant";
import debounce from 'lodash/debounce'
import GoodsList from "../../components/GoodsList/index.vue";
import { mapState } from "vuex";
export default {
  name: "Search",
  components: {
    [Search.name]: Search,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Cell.name]: Cell,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Switch.name]: Switch,
    GoodsList,
  },
  data() {
    return {
      keyword: "", //''
      // 确定搜索
      isSearch: true, 
      // 1为搜索 2为搜索提示 3为搜索内容
      // true为搜索提示 false为搜索内容
      // 下拉菜单
      currentIndex: 0,
      navList:[],
      categoryId:0,
      // 最高价
      upperPrice:'',
      // 最低价
      floorPrice:'',
      // 默认升序 1 升 2降低
      descSorted:undefined,
      historyList:JSON.parse(localStorage.getItem('history_list')) || []
    };
  },
  mounted() {
    
    this.getPopularList();

  },

  methods: {
    // 判断
      inspect(){
        let {upperPrice,floorPrice} = this
            
          if(Number(upperPrice)&&Number(floorPrice)){
            // 转为数字都为true则判断
            if(upperPrice > 0 && floorPrice > 0){
              return{
                upperPrice,
                floorPrice
              }
            }else{
              return{
                upperPrice:-1,
                floorPrice:-1
              }
            }

          }else{
            return {
              upperPrice:-1,
              floorPrice:-1
            }

          }


      },
      // 点击改变升序还是降序
      changeSort(flag){
        this.descSorted = flag
      },
    //根据id发送请求 
    categoryRequest(categoryId,index){
      this.currentIndex = index
      this.categoryId = categoryId
      let {upperPrice,floorPrice}  =  this.inspect()
      this.$store.dispatch('getGoodsList',{keyword:this.keyword,categoryId:this.categoryId,upperPrice,floorPrice,descSorted:this.descSorted})
    },
    // 点击热门发送请求
    popularGoods(keyword){
      this.keyword = keyword
      this.isSearch = false
       this.inspect()
       let {upperPrice,floorPrice}  =  this.inspect()
      this.$store.dispatch('getGoodsList',{keyword:this.keyword,categoryId:this.categoryId,upperPrice,floorPrice,descSorted:this.descSorted})
      this.getPopularList()
    },
    // 点击历史记录 和 列表展示区 发送请求
    totalGetGoods(keyword){
      this.keyword = keyword
      this.onSearch(keyword)
    },
    // 按下空格键触发
    onSearch(val) {
      let history = this.historyList
  
     let index =  history.findIndex(item => item === val)
      // 如果不存在
      if(index === -1){
        // 我们则判断数组的长度是否小于10
        if(history.length < 10){
          // 如果小于我们则添加进去
          history.unshift(val)
        }else{
          // 如果大于或者等于我们则删除最后一项并添加到最前面
            history.pop()
            history.unshift(val)

        }

      }else{
        // 如果存在 我们要删除他对应的位置并把它放到第一个
        history.splice(index,1)
        history.unshift(val)
        
      }
      localStorage.setItem('history_list',JSON.stringify(history))

      this.isSearch = false
        let {upperPrice,floorPrice}  =  this.inspect()
      this.$store.dispatch('getGoodsList',{keyword:this.keyword,categoryId:this.categoryId,upperPrice,floorPrice,descSorted:this.descSorted})


    },
    // 点击取消时触发
    onCancel() {
      let redirect = this.$route.query.redirect || '/'
      this.$router.push(redirect)

    },
    //输入框文本发生改变时触发
    input: debounce(function(value){
        // this.isSearch = true
        if(!value.leng && value.trim() === "") return
        this.keyword = value.replace(/\s*/g,"")
        this.$store.dispatch('getNavigationList',this.keyword)
        // console.log("输入框文本发生改变时触发，input");
    },500),
    // 输入框获取焦点的时候
    focus(val) {
        this.isSearch = true
      // console.log("输入框获取焦点的时候，focus");
    },
    // 小图标点击时候
    clear() {
      // 小图标
      this.isSearch = true
      // console.log("清除,clear");
    },
    // 下拉菜单
    onConfirm(flag) {
      if(flag){
        // 点击确定 判断值有无发生变化 
       if(this.upperPrice === '' && this.floorPrice === '' && this.descSorted === undefined){
         this.$refs.item.toggle();
         return
       }
      }else{
        // 点击取消
        this.$refs.item.toggle();
        return
      }
      let {upperPrice,floorPrice}  =  this.inspect()
      this.$store.dispatch('getGoodsList',{keyword:this.keyword,categoryId:this.categoryId,upperPrice,floorPrice,descSorted:this.descSorted})
      this.$refs.item.toggle();
    },
    // 获取热门推荐的数据
    getPopularList() {
      this.$store.dispatch("getPopularList");
    },
    // 清楚所有本地缓存
    clearhHistoryList(){
      this.historyList = []
      localStorage.removeItem('history_list')
    }
  },
  computed: {
    ...mapState({
      popularList: (state) => state.search.popularList,
      navigationList:(state) =>state.search.navigationList,
      category1List:state => state.search.category1List
    }),
  },
  watch:{
    navigationList:{
      deep:true,
      handler(newValue){
        // if(newValue.length){
        //   this.navList = newValue
        // }else{
        //   this.navList = []
        //   // this.keyword = ''
        //   // Dialog({ message: '您输入的商品不存在，请重新输入' });
        // }
        this.navList = newValue.length ? newValue : []
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import url("../../assets/resetcss.css");
// 头部搜索
.searchFather {
  width: 100%;
  height: 48px; //48
  position: relative;
  &.active {
    height: 88px;
  }
  .diopDownItem {
    z-index: 1;
    width: 100%;
    position: fixed;
    top: 48px;
    .detault {
      width: 100%;
      padding-left: 20px;
      height: 50px;
      line-height: 60px;
    }
    .yes {
      width: 50%;
      height: 51px;
      background-color: #fff;
      outline: none;
      border: none;
      box-sizing: border-box;
      border-top: 1px solid #d9d9d9;
      border-left: 1px solid #d9d9d9;
      color: #dd1a21;
    }
    .no {
      width: 50%;
      height: 51px;
      box-sizing: border-box;
      background-color: #fff;
      outline: none;
      border: none;
      border-top: 1px solid #d9d9d9;
    }
    // 弹出框的内容区样式
    ::v-deep .van-dropdown-menu__bar {
      height: 40px;
      background-color: #fafafa;
    }
    .vantTag {
      margin: 20px 20px 2px 25px;
      padding: 8px;
    }
    .sort {
      height: 28px;
      width: 290px;
      margin: 20px 0;
      padding: 0px 15px 0 15px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .button {
        width: 102px;
        height: 26px;
        background-color: #ffffff;

        outline: none;
        border: none;
        border: 1px solid #7f7f7f;
        &.active {
          color: red;
          border: 1px solid #dd1a21;
        }
      }
    }
    .content {
      padding: 0px 15px 0 15px;
      height: 28px;
      width: 100%;
      margin-top: 20px;
      // background-color: red;
      display: flex;
      justify-content: space-around;
      align-items: center;
      input {
        width: 133px;
        height: 26px;
        border: 1px solid #7f7f7f;
        text-align: center;
      }
    }
  }
}
.van-search {
  padding-top: 8px;
  width: 375px;
  top: 0;
  position: fixed;
  z-index: 1;
  .van-search__content {
    border-radius: 5px;
    height: 30px;
    padding: 0 10px;
    // background-color: aqua;
  }
}
// 底部存储区
.footer {
  width: 100%;
  height: 294px;
  .popular {
    width: 100%;
    height: 142px;
    .header {
      width: 360px;
      padding: 5px 0 0 15px;
      margin-top: 5px;
      margin-bottom: 5px;
      .text {
        color: #999999;
        font-size: 15px;
      }
      .van-icon-delete-o {
        font-size: 20px;
      }
    }
    .navList {
      width: 355px;
      // height: 109px;
      padding: 10px 0px 0 15px;
      // background-color: aqua;
      .van-tag {
        margin-right: 12px;
        margin-bottom: 15px;
      }
    }
  }
  .storage {
    width: 100%;
    // height: 142px;
    border-bottom: 10px solid #eeeeee;
    .header {
      width: 360px;
      padding: 5px 0 0 15px;
      display: flex;
      justify-content: space-between;
      margin-bottom: 5px;
      .text {
        color: #999999;
        font-size: 15px;
      }
      .van-icon-delete-o {
        font-size: 20px;
      }
    }
    .navList {
      width: 335px;
      // height: 109px;
      // margin-bottom: 20px;
      padding: 10px 0px 0 15px;
      // background-color: aqua;
      .van-tag {
        margin-right: 15px;
        margin-bottom: 15px;
      }
    }
  }
}
// 分类展示的数据
.exhibition {
  width: 100%;
  height: calc(100vh - 88px);
  padding-bottom: 40px;
  background-color: #eeeeee;
}
</style>
